package ui;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import manager.FileManagerImpl;
import manager.HistogramManagerImpl;
import org.jfree.ui.RefineryUtilities;

import Exception.SystemException;
import entity.Histogram;
import entity.Image;

/**
 * Classe que representa o frame de inclusão de dados no sistema
 *
 * @author Gutemberg Rodrigues
 */

public class FrameInput extends javax.swing.JFrame {

    public FrameInput() {
        initComponents();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        painelR.setVisible(false);
        painelL.setVisible(false);
    }

    @SuppressWarnings("unchecked")

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtPath = new javax.swing.JTextField();
        bntBusca = new javax.swing.JButton();
        comboFuncao = new javax.swing.JComboBox();
        labelInfo1 = new javax.swing.JLabel();
        labelInfo2 = new javax.swing.JLabel();
        bntPro = new javax.swing.JButton();
        bntLimpar = new javax.swing.JButton();
        painelL = new javax.swing.JPanel();
        txtL = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        painelR = new javax.swing.JPanel();
        txtRMax = new javax.swing.JTextField();
        txtRMin = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(204, 204, 204), null, null));

        txtPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPathActionPerformed(evt);
            }
        });

        bntBusca.setText("...");
        bntBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntBuscaActionPerformed(evt);
            }
        });

        comboFuncao.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Exibir Histograma", "Equalização", "Normalização" }));
        comboFuncao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboFuncaoActionPerformed(evt);
            }
        });

        labelInfo1.setText("Caminho da Imagem:");

        labelInfo2.setText("Funções do Sistema:");

        bntPro.setText("Processar");
        bntPro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntProActionPerformed(evt);
            }
        });

        bntLimpar.setText("Limpar Campo");
        bntLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntLimparActionPerformed(evt);
            }
        });

        jLabel1.setText("L");

        javax.swing.GroupLayout painelLLayout = new javax.swing.GroupLayout(painelL);
        painelL.setLayout(painelLLayout);
        painelLLayout.setHorizontalGroup(
            painelLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelLLayout.createSequentialGroup()
                .addGroup(painelLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painelLLayout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addComponent(jLabel1))
                    .addGroup(painelLLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txtL, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        painelLLayout.setVerticalGroup(
            painelLLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelLLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

        txtRMax.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtRMaxActionPerformed(evt);
            }
        });

        jLabel3.setText("R Min");

        jLabel2.setText("R Máx");

        javax.swing.GroupLayout painelRLayout = new javax.swing.GroupLayout(painelR);
        painelR.setLayout(painelRLayout);
        painelRLayout.setHorizontalGroup(
            painelRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painelRLayout.createSequentialGroup()
                .addGroup(painelRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(painelRLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txtRMax, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                        .addComponent(txtRMin, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(painelRLayout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 142, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addGap(62, 62, 62)))
                .addContainerGap())
        );
        painelRLayout.setVerticalGroup(
            painelRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painelRLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(painelRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(painelRLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtRMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(bntLimpar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 409, Short.MAX_VALUE)
                        .addComponent(bntPro, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(txtPath, javax.swing.GroupLayout.DEFAULT_SIZE, 554, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bntBusca))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(labelInfo1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 508, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(labelInfo2)
                            .addComponent(comboFuncao, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31))))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(painelL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(painelR, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(75, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelInfo1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bntBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addComponent(labelInfo2)
                .addGap(18, 18, 18)
                .addComponent(comboFuncao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(painelL, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(painelR, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bntPro)
                    .addComponent(bntLimpar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }

    private void txtPathActionPerformed(java.awt.event.ActionEvent evt) {
       
    }

    private void bntBuscaActionPerformed(java.awt.event.ActionEvent evt) {
        txtPath.setText(iniFileChooser());
        
    }

    private void bntLimparActionPerformed(java.awt.event.ActionEvent evt) {
       txtPath.setText(null);
       txtL.setText(null);
       txtRMin.setText(null);
       txtRMax.setText(null);
    }
    
    private void checkClean(){
    	
    	if(comboFuncao.getSelectedItem().toString().equals("Normalização")){
            if(txtPath.getText().length() == 0 || txtL.getText().length() == 0  || txtRMax.getText().length() == 0 || txtRMin.getText().length() == 0){
            	JOptionPane.showMessageDialog(this, "Campo não informado",
                        "Atenção", JOptionPane.ERROR_MESSAGE);
            	throw new SystemException("Campo da Tela em Branco!", null);
            }
        }else if(comboFuncao.getSelectedItem().toString().equals("Equalização")){
        	if(txtPath.getText().length() == 0 || txtL.getText().length() == 0){
            	JOptionPane.showMessageDialog(this, "Campo não informado",
                        "Atenção", JOptionPane.ERROR_MESSAGE);
            	throw new SystemException("Campo da Tela em Branco!", null);
        	}
        } else if(comboFuncao.getSelectedItem().toString().equals("Exibir Histograma")){
        	if(txtPath.getText().length() == 0){
            	JOptionPane.showMessageDialog(this, "Campo não informado",
                        "Atenção", JOptionPane.ERROR_MESSAGE);
            	throw new SystemException("Campo da Tela em Branco!", null);
        	}
        }

    }

    private void bntProActionPerformed(java.awt.event.ActionEvent evt) {
    		checkClean();
    	
	    	if(comboFuncao.getSelectedItem().toString().equals("Normalização")){
	            functionExpansao();
	        }else if(comboFuncao.getSelectedItem().toString().equals("Equalização")){
	            functionEqualizacao();
	        } else if(comboFuncao.getSelectedItem().toString().equals("Exibir Histograma")){
	        	functionHistogram();
	        }
    	
    }
    
    private void functionExpansao(){
    	
    	try{
	    	FileManagerImpl impl = new FileManagerImpl();
	    	HistogramManagerImpl hist = new HistogramManagerImpl();
	    	JButton bt = new JButton();
	    	Image image = impl.generateImage(txtPath.getText());
	    	Histogram histogram = hist.histogramExpansion(image, Integer.parseInt(txtRMax.getText()), Integer.parseInt(txtRMin.getText()), Integer.parseInt(txtL.getText()));
	    	Image newImage = impl.generatePGM(histogram, image);
	    	
	    	final HistogramVisualization visualization = new HistogramVisualization("Histogram", newImage);
	    	visualization.add(bt);
			visualization.pack();  
			RefineryUtilities.centerFrameOnScreen(visualization);  
			visualization.setVisible(true);
			
			bt.setText("x");
			bt.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	visualization.setVisible(false);
	            }
	        });
			
			JOptionPane.showMessageDialog(this, "Processo Finalizado!", "Fim", JOptionPane.INFORMATION_MESSAGE);
   
    	}catch(Exception e){
		JOptionPane.showMessageDialog(this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
    	}
    }
    
    private void functionEqualizacao(){
    	try{
	    	FileManagerImpl impl = new FileManagerImpl();
	    	HistogramManagerImpl hist = new HistogramManagerImpl();
	    	JButton bt = new JButton();
	    	Image image = impl.generateImage(txtPath.getText());
	    	Histogram histogram = hist.histogramEqualization(image.getHistogram(), image, Integer.parseInt(txtL.getText()));//(image, 187, 0, 256);
	    	Image newImage = impl.generatePGM(histogram, image);
	    	
	    	final HistogramVisualization visualization = new HistogramVisualization("Histogram", newImage);
	    	visualization.add(bt);
			visualization.pack();  
			RefineryUtilities.centerFrameOnScreen(visualization);  
			visualization.setVisible(true);
			
			bt.setText("x");
			bt.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	visualization.setVisible(false);
	            }
	        });
			
			JOptionPane.showMessageDialog(this, "Processo Finalizado!", "Fim", JOptionPane.INFORMATION_MESSAGE);
    	}catch(Exception e){
		JOptionPane.showMessageDialog(this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
    	}
    }
    
    private void functionHistogram(){
    	try{
	    	FileManagerImpl impl = new FileManagerImpl();
	    	Image image = impl.generateImage(txtPath.getText());
	    	JButton bt = new JButton();
	    	final HistogramVisualization visualization = new HistogramVisualization("", image);
	    	bt.setBounds(498, 230,10,10);
	    	visualization.add(bt);
			visualization.pack();  
			RefineryUtilities.centerFrameOnScreen(visualization);	
			visualization.setVisible(true);
			
			bt.setText("x");
			bt.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	visualization.setVisible(false);
	            }
	        });
			
			visualization.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

			JOptionPane.showMessageDialog(this, "Processo Finalizado!", "Fim", JOptionPane.INFORMATION_MESSAGE);
    	}catch(Exception e){
    		JOptionPane.showMessageDialog(this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void txtRMaxActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void comboFuncaoActionPerformed(java.awt.event.ActionEvent evt) {

        if(comboFuncao.getSelectedItem().toString().equals("Normalização")){
            painelR.setVisible(true);
            painelL.setVisible(true);
        }else if(comboFuncao.getSelectedItem().toString().equals("Equalização")){
            painelR.setVisible(false);
            painelL.setVisible(true);
        } else if(comboFuncao.getSelectedItem().toString().equals("Exibir Histograma")){
            painelR.setVisible(false);
            painelL.setVisible(false);
        }

    }

    private String iniFileChooser(){
        jFileChooser = new JFileChooser();
        JFrame frame = new JFrame();
        jFileChooser.setVisible(true);
        jFileChooser.showOpenDialog(frame);
        String path = "";
        if(jFileChooser.getSelectedFile()!=null){
            path = jFileChooser.getSelectedFile().getAbsolutePath();
        }
        return path;
    }

    public void openFrameInput(){
         FrameInput frameInput = new FrameInput();
         frameInput.setVisible(true);
         frameInput.setLocationRelativeTo(null);
    }

    private javax.swing.JButton bntBusca;
    private javax.swing.JButton bntLimpar;
    private javax.swing.JButton bntPro;
    private javax.swing.JComboBox comboFuncao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelInfo1;
    private javax.swing.JLabel labelInfo2;
    private javax.swing.JPanel painelL;
    private javax.swing.JPanel painelR;
    private javax.swing.JTextField txtL;
    private javax.swing.JTextField txtPath;
    private javax.swing.JTextField txtRMax;
    private javax.swing.JTextField txtRMin;
    private JFileChooser jFileChooser;
}
